package com.peanut.wapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.peanut.wapp.controller.req.GetNewsDetailParam;
import com.peanut.wapp.controller.req.GetNewsListParam;
import com.peanut.wapp.controller.res.BaseResult;
import com.peanut.wapp.controller.res.ListResult;
import com.peanut.wapp.controller.res.ObjectResult;
import com.peanut.wapp.controller.res.PageResult;
import com.peanut.wapp.controller.resBean.RNewsBean;
import com.peanut.wapp.service.NewsService;
import com.peanut.wapp.service.exception.ServiceException;
import com.peanut.wapp.util.NumUtil;

@Controller
@RequestMapping(value ="/news", produces = "application/json")
public class NewsController {
	Logger logger = Logger.getLogger(NewsController.class);

	@Autowired
	NewsService newsServiceImpl;
	
	@RequestMapping("/v1/getDetail")
	@ResponseBody
	public ObjectResult<RNewsBean> getDetail(@Validated GetNewsDetailParam param, BindingResult error, HttpServletRequest request, HttpServletResponse response) {
		ObjectResult<RNewsBean> res = new ObjectResult<RNewsBean>();
		if (error.hasErrors()) {
			res.setRescode(BaseResult.param.getCode());
			res.setMsg(error.getFieldError().getDefaultMessage());
			return res;
		}
		String nid = param.getNid();
		try {
			RNewsBean news = newsServiceImpl.getDetail(nid);
			res.setFlag(news!=null);
			res.setData(news);
			
		} catch (ServiceException e) {
			res.setServiceException(e);
		}
		return res;
	}
	
	
	/**
	 * 获取用户列表
	 **/
	@RequestMapping("/v1/list")
	@ResponseBody
	public ListResult<RNewsBean> list(GetNewsListParam param, HttpServletRequest request, HttpServletResponse response) {
		ListResult<RNewsBean> result = new ListResult<RNewsBean>();
		try {
			int page = NumUtil.toInt(param.getPage(), 0);
			int pageSize = NumUtil.toInt(param.getPageSize(), 20);

			PageResult<RNewsBean> resData = newsServiceImpl.getList(page, pageSize);
			if (resData != null) {
				result.setTotalSize(resData.getCount());
				result.setData(resData.getData());
			}
			result.setPage(page);
		} catch (ServiceException e) {
			result.setServiceException(e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setServiceException(new ServiceException("error", "获取异常"));
		}
		return result;
	}
	
}
